<!--
    group: 发票管理
    name: 开票列表
    item: 邀请验证---（展示核验列表弹层）
-->
<template>
   <a-modal
      wrapClassName="invitationCodeNew-con"
      :width="1000"
      :title="title_"
      :visible="visible_"
      @cancel="handleCancel"
      :footer="null"
    >
    <a-alert message="当前开票数据已与其他开票请求合并核验，您可以：" type="warning" show-icon  />
    <a-card title="邀请法人完成全部开票信息核验" style="width: 100%;margin: 5px 0;" :headStyle="{padding:'3px 10px','font-size':'14px',display:'flex','font-weight':'600'}">
      <a-table :columns="columns" :data-source="dataSource" bordered :pagination="false" :scroll="{y:300}">
        <template slot="name" slot-scope="text">
          <divBox :dataArr="text"></divBox>
        </template>
        <template slot="money" slot-scope="text">
          <divBox :dataArr="text" direction="right"></divBox>
        </template>
        <template slot="signUrl" slot-scope="text,record">
          <div class="code">
            <img class="img" :src="text" alt="二维码图片">
            <!-- <p class="tips" v-if="codeShow">复制成功</p> -->
            <!-- <a-button type="primary" @click="upDown(record)" :size="'small'">复制二维码</a-button> -->
          </div>
        </template>
        <template slot="signSMS" slot-scope="text,record">
          {{text.label}} <a :href="text.url">{{text.url}}</a>
          <!-- <a-button type="primary" style="margin: 0 20px;" @click="resendEvent(record)" :size="'small'"> 重新发送核验邀请 </a-button> -->

        </template>

        <template slot="footer" slot-scope="currentPageData" >
          <div style="display: flex; justify-content: flex-end; align-items: center; padding-right: 0px;">
            <a-button type="primary" style="margin: 0 20px;"  @click="resendEvent()" > 重新发送核验邀请 </a-button>
            <a-button type="primary" style="margin: 0 20px;" @click="upDown()"> 下载二维码 </a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    <a-card title="为当前开票请求单独发送核验邀请" style="width: 100%; margin: 5px 0; " :headStyle="{padding:'3px 10px','font-size':'14px',display:'flex','font-weight':'600'}" :bodyStyle="{padding:'20px 200px'}">
      <a-button type="primary" block @click.prevent="InvitationVerification"> 邀请核验 </a-button>
    </a-card>
    </a-modal>
</template>

<script>
import QRious from 'qrious'
import UUID from '@/utils/uuid'
import * as Util from '@/utils/util'
import {
  getInvoiceSignUrl, getTaxInvoiceCheckSendSms,getCatalogSignAuthSMS,getInvoiceBaseUrl,
  getInvoiceReturnSignUrl,getTaxReturnTicketBatchCheck
} from '@api/invoiceAdminister'
// {"invoiceId":1000000342,"entId":null,
// "entName":"沙市区千城万店方略信息咨询服务中心",
// "legalName":"陈志新","legalPhone":"13804984417",
// "signSMS":"尊敬的沙市区千城万店方略信息咨询服务中心，您有开票信息待确认，点击以下链接确认信息并完成验证。https://t.bestsign.cn/ph3Nx2uhZ8Pda5",
// "signUrl":"https://t.bestsign.cn/ph3Nx2uhZ8Pda5",
// "catalogName":"75803489241c4b5d8cb0cdfcb089de52","receiptName":"普票","amount":5656}
const columns = [
  {
    title: '购买方名称',
    align:'center',
    width:'300px',
    dataIndex: 'entName',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '开票金额',
    align:'center',
    width:'150px',
    className: 'column-money',
    dataIndex: 'amount',
    scopedSlots: { customRender: 'money' },
  },
  {
    title: '已发送核验短信',
    align:'center',
    width:'300px',
    dataIndex: 'signSMS',
    scopedSlots: { customRender: 'signSMS' },
  },
  {
    title: '核验二维码',
    align:'center',
    width:'150px',
    dataIndex: 'signUrl',
    scopedSlots: { customRender: 'signUrl' },
  },
]



const conv = (dataList,currentData)=>{
  // console.log('conv 0====>',dataList);
  const tempObj = {}
  const kkk = currentData.id
  const className='red'
  const getVal = (key,val)=>{
    if(key==kkk){
      return {value:val,className}
    }
    return val
  }

  dataList.forEach(item=>{
    const {signSMS,signUrl,invoiceId,catalogName} = item
    const key =catalogName // UUID('MDUUID',JSON.stringify(signUrl))
    if(!tempObj[key]){
      tempObj[key] = {
        signUrl,signSMS,invoiceId,
        amount:[getVal(item.invoiceId,item.amount)],
        entName:[getVal(item.invoiceId,item.entName)],
        keys:[getVal(item.invoiceId,item.invoiceId)]
      }
    }else{
      tempObj[key].amount.push(getVal(item.invoiceId,item.amount))
      tempObj[key].entName.push(getVal(item.invoiceId,item.entName))
      tempObj[key].keys.push(getVal(item.invoiceId,item.invoiceId))
    }
  })
  // console.log('conv 1====>',tempObj);
  const tempArr = []
  for (const key in tempObj) {
    if (Object.hasOwnProperty.call(tempObj, key)) {
      const element = tempObj[key];
      tempArr.push(element)
    }
  }
  return tempArr
}

const divBox = {
  props: {
    dataArr: { type: Array },
    direction:{type:String,default:'center'},
    className:{type:String,default:''},
    // setEvent: { type: Function },
  },
  data() {
    return {}
  },
  methods: {
    getItem(item,direction,className){
      const directionAction = {
        'left':'t-l',
        'center':'t-c',
        'right':'t-r',
      }
      if(this.isType.isObject(item)){
        return (<div class={`div-box-item ${directionAction[direction]} ${item.className}`}>
          {item.value}
        </div>)
      }
      return(<div class={`div-box-item ${directionAction[direction]} ${className}`}>
        {item}
      </div>)
    },
  },
  render: function (h) {
    const {dataArr,direction,className} = this

    return (<div class={'div-box-c'}>
      {dataArr.map(item=>(this.getItem(item,direction,className)))}
    </div>)
  },
}


export default {
  // import引入的组件需要注入到对象中才能使用
  name: 'invitationCodeNew',
  components: {divBox},
  props: {
    rowData: {
      type: [Object,Array],
      required: true,
    },
    oldData:{type:Object},
    show:{type:Boolean,default:false},
    event:{type:Function}
  },
  data() {
    // 这里存放数据
    return {
      visible_:false,
      title_:'邀请验证',
      columns,
      dataSource:[],
      dataSource_:[],
      codeText: '发送短信',
      codeShow:false
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    rowData: {
      handler(val) {
        if(!this.isType.isNullOrUnDef(val)){
          this.dataSource = conv(this.convData(val),this.oldData)
        }
      },
      deep: true,
      immediate: true
    },

    show: {
      handler(val) {
        if(!this.isType.isNullOrUnDef(val) && this.isType.isBoolean(val)){
          this.visible_ = val
        }
      },
      deep: true,
      immediate: true
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  // 方法集合
  methods: {
    resendEvent(){
      const {catalogName,signAuthId} = this.rowData[0]
      // const rowData = this.rowData
      // const invoiceIdArr = []
      // rowData.forEach(item=>{
      //   invoiceIdArr.push(item.invoiceId)
      // })
      // console.log('====>',rowData);
      // let params = {data:{ids:invoiceIdArr}};
      // getTaxInvoiceCheckSendSms(params).then(res => {
      //     if (res.success) {
      //       this.$message.success('发送成功');
      //       // this.textShow = true;
      //       // this.countDown(60);
      //     }else{
      //       this.$message.warning(res.message);
      //     }
      //   })
      const params = {catalogName,signAuthId}
      getCatalogSignAuthSMS(params).then(res=>{
        if (res.success) {
          const url = res.result
          this.dataSource[0].signSMS.url = url
          this.dataSource[0].signUrl = this.getBaseUrl(url)
          this.$message.success('发送成功');
        }else{
          this.$message.warning(res.message);
        }
      })

    },

    convData(val){
      const tempArr = []
      if(this.isType.isArray(val)){
        val.forEach(async item=>{
          const {signUrl,signSMS,amount, invoiceId} = item
          const tempAmount = Util.conversionElement(amount)+' 元'
          const signSMS_ = signSMS.replace(signUrl,'')
          const temp =  this.getBaseUrl(signUrl)
          tempArr.push({...item,signUrl:temp,amount:tempAmount,signSMS:{label:signSMS_,url:signUrl}})
        })
      }
      this.dataSource_ = tempArr
      // console.log(tempArr);
      return tempArr
    },
    getBaseUrl(url){
      var qr = new QRious({
        // background: 'green',
        // backgroundAlpha: 0.8,
        // foreground: 'blue',
        // foregroundAlpha: 0.8,
        level: 'H',
        // padding: 5,
        // size: 100,
        value: url
      });
      return qr.toDataURL()
    },
    handleCancel(){
      this.visible_ = false
      this.event&& this.event('close',this.visible_)
    },
    /**
     * 单独发送核验邀请
     */
    InvitationVerification(){
      // 需要获取到  提示用户该条开票申请已绑定其他数据，列表中当前数据标红展示：
      const tempId = this.oldData.id
      let params = {data:{ids:[tempId]}};
      getInvoiceSignUrl(params).then(res=>{
        if(res.success==true){
          const url = res.result
          const temp = []
          this.rowData.forEach(item=>{
            const {invoiceId} = item
            if(tempId==invoiceId){
              const signSMS_ = item.signSMS.replace(item.signUrl,'')
              temp.push({...item,signUrl:url,signSMS:signSMS_+url})
            }
          })
          this.event&& this.event('IV',temp)
        }else{
          this.$message.warning(res.message);
        }
      })
    },
     //复制二维码
     upDown(){
      const record = this.dataSource[0]
      const {signUrl} =record
      console.log('复制二维码==>',record)
      if (signUrl){
        const imgUrl = signUrl;
        // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          var bstr = atob(imgUrl.split(',')[1]);
          var n = bstr.length;
          var u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          var blob = new Blob([u8arr]);
          window.navigator.msSaveOrOpenBlob(blob, 'code' + '.' + 'png');
        } else {
          // 这里就按照chrome等新版浏览器来处理
          const a = document.createElement('a');
          a.href = imgUrl;
          a.setAttribute('download', 'code');
          a.click();
        }

        // this.$message.success('复制成功');
        this.codeShow = true;
      }
    },

  },
  }
</script>
<style lang='less' >
.invitationCodeNew-con{
  .ant-modal{
    .ant-modal-content{
      .ant-modal-header{
        .ant-modal-title{
          text-align:left;
        }
      }
    }
  }
  .ant-table-tbody > tr > td{
    padding:0;
  }
  .div-box-c{
    width: 100%;
    display: flex;
    justify-content:center;
    align-items: center;
    flex-direction: column;
    .div-box-item{
      width: 100%;
      height: 50px;
      display: flex;
      justify-content:center;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
      padding: 5px 8px;
      &.t-c{
        justify-content:center;
      }
      &.t-l{
        justify-content:flex-start;
      }
      &.t-r{
        justify-content:flex-end;
      }
      &.red{
        color: #fa0505;
        font-weight: bold;
      }
    }
    .div-box-item:last-child{
      border-bottom: 0px solid #e8e8e8;
    }
  }
  .tips{
    background: rgba(43, 162, 69, 0.38);
    border-radius: 20px;
    text-align: center;
    color: #FFFFFF;
  }
}
</style>
